package com.example.transit.utils.UpdataAppUtil;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;


import java.io.File;

public class DownLoadUtils {
    private static DownLoadUtils downLoadUtis;
    private Context context;
    public static final String TASK_PATH = Environment
            .getExternalStorageDirectory().toString() + "/transit/Download/";//下载文件路径 任务生成缩略图保存路径

    public static DownLoadUtils getInstance() {
        if (downLoadUtis == null) {
            downLoadUtis = new DownLoadUtils();
        }
        return downLoadUtis;
    }

    public void init(Context context) {
        this.context = context;
    }

    /**
     * @param url      apk 下载地址
     * @param fileName 下载文件名称
     */
    public void downLoadNewApk(String url, final String fileName) {
        final File downLoadPath = new File(TASK_PATH);
        if (!downLoadPath.exists()) {
            downLoadPath.mkdirs();
        }
        Log.e("ssss", "downLoadPath==>" + downLoadPath);
        Log.e("ssss", "fileName==>" + fileName);

        File apkFile = new File(downLoadPath, fileName);
        if (apkFile.exists()) {
            //已下载过
            Toast.makeText(context, "已下载过，请在通知栏下安装", Toast.LENGTH_SHORT);
            NotificationUtils.getInstance().alreadyDownLoad(downLoadPath.getAbsolutePath() + "/" + fileName);
            return;
        }
        NotificationUtils.getInstance().startDownLoad();

        DownloadUtil.getInstance().download(url, TASK_PATH, fileName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(String path) {
                Toast.makeText(context, "下载完成，请在通知栏点击安装", Toast.LENGTH_SHORT);
                NotificationUtils.getInstance().downloadSuccess(downLoadPath.getAbsolutePath() + "/" + fileName);

            }

            @Override
            public void onDownloading(int total, int progress) {
                NotificationUtils.getInstance().isDownLoading(total, progress);

            }

            @Override
            public void onDownloadFailed() {
                NotificationUtils.getInstance().downLoadFail();
            }
        });

    }
}
